#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版图片爬虫
使用配置文件中的设置
"""

import os
import requests
import json
import time
import hashlib
from PIL import Image
import io
from config import *

def download_and_process_image(url, filename):
    """下载并处理图片"""
    try:
        response = requests.get(url, timeout=DOWNLOAD_TIMEOUT)
        if response.status_code == 200:
            # 处理图片
            img = Image.open(io.BytesIO(response.content))
            
            # 转换为RGB模式
            if img.mode in ('RGBA', 'LA', 'P'):
                img = img.convert('RGB')
            
            # 调整大小
            img.thumbnail((MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT), Image.Resampling.LANCZOS)
            
            # 保存
            os.makedirs('downloaded_images', exist_ok=True)
            local_path = os.path.join('downloaded_images', filename)
            img.save(local_path, 'JPEG', quality=IMAGE_QUALITY)
            
            return local_path
    except Exception as e:
        print(f"处理图片失败 {url}: {e}")
        return None

def get_sample_flower_images():
    """获取示例鲜花图片URL（无需API）"""
    # 这里提供一些免费的示例图片URL
    sample_images = [
        {
            'category': 'roses',
            'urls': [
                'https://images.unsplash.com/photo-1518895949257-7621c3c786d7?w=800',
                'https://images.unsplash.com/photo-1561181286-d3fee7d55364?w=800',
                'https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800'
            ]
        },
        {
            'category': 'tulips', 
            'urls': [
                'https://images.unsplash.com/photo-1520637836862-4d197d17c93a?w=800',
                'https://images.unsplash.com/photo-1584464491033-06628f3a6b7b?w=800'
            ]
        },
        {
            'category': 'sunflowers',
            'urls': [
                'https://images.unsplash.com/photo-1597848212624-e6f9e1d7edb1?w=800',
                'https://images.unsplash.com/photo-1470509037663-253afd7f0f51?w=800'
            ]
        }
    ]
    
    results = []
    
    for category_data in sample_images:
        category = category_data['category']
        print(f"处理 {category} 类别...")
        
        for i, url in enumerate(category_data['urls']):
            filename = f"{category}_{i+1}.jpg"
            local_path = download_and_process_image(url, filename)
            
            if local_path:
                results.append({
                    'category': category,
                    'filename': filename,
                    'local_path': local_path,
                    'original_url': url
                })
                print(f"  下载成功: {filename}")
            
            time.sleep(REQUEST_DELAY)
    
    # 保存结果
    with open('sample_flower_images.json', 'w', encoding='utf-8') as f:
        json.dump(results, f, ensure_ascii=False, indent=2)
    
    print(f"\n完成！共处理 {len(results)} 张图片")
    return results

if __name__ == "__main__":
    print("=== 简化版鲜花图片下载器 ===")
    print("注意：这个版本使用示例图片，无需API密钥")
    
    results = get_sample_flower_images()
    
    print("\n下载的图片:")
    for result in results:
        print(f"  {result['category']}: {result['filename']}")